<template>
  <div class="home-main">
    <header>全文上传翻译Demo</header>
    <div class="main-bfc">
      <section class="main-wrap">
        <div class="upload-container flex-center" v-if="!tableList.length">
          <div class="flex-column-center">
            <img src="@/assets/images/folder-upload.png" alt="" />
            <p class="tip">上传格式：PDF</p>
            <p class="tip">文件大小：36M/文件</p>
            <p class="tip">存储空间：1G</p>
            <el-upload
              id="el-upload"
              class="upload-wrap mt20"
              ref="uploadRef"
              accept=".pdf"
              :auto-upload="false"
              :http-request="uploadFile"
              :show-file-list="false"
              :on-change="changeFile"
            >
              <div class="upload-btn">上传文件</div>
            </el-upload>
          </div>
        </div>
        <div class="table-container" v-if="tableList.length">
          <div class="top-header flex-center-between">
            <div class="tip">上传格式：PDF；单个文档不超过36M；存储空间：1G</div>
            <el-upload
              id="el-upload"
              class="upload-wrap"
              ref="uploadRef"
              accept=".pdf"
              :auto-upload="false"
              :http-request="uploadFile"
              :show-file-list="false"
              :on-change="changeFile"
            >
              <div class="upload-btn flex-center">
                <img class="upload-img" src="@/assets/images/upload-icon.png" alt="" />
                上传文件
              </div>
            </el-upload>
          </div>
          <div class="table-wrap mt20">
            <el-table :data="tableList" border stripe style="width: 100%" header-row-class-name="table-header">
              <el-table-column label="题名" show-overflow-tooltip>
                <template #default="scope">
                  <div class="flex-align-center">
                    <img class="file-type-img" src="@/assets/images/upload-pdf-icon.png" alt="" srcset="" />
                    <span>{{ scope.row.fileName }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="状态" width="250">
                <template #default="scope">
                  <span v-show="scope.row.translateState != 100 || !scope.row.docMd5" class="jxz-status stauts">解析中</span>
                  <span v-if="scope.row.docMd5 && scope.row.translateState == 100">
                    <a class="mr10 href-text" target="_blank" :href="`https://yfzx-test.cnki.net/translate/generate/${scope.row.docMd5}/mix.html`"
                      >译文模式</a
                    >
                    <a class="href-text" target="_blank" :href="`https://yfzx-test.cnki.net/translate/generate/${scope.row.docMd5}/compare.html`"
                      >对照模式</a
                    >
                  </span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </section>
    </div>
  </div>
</template>

<script>
export default { name: 'Home' }
</script>

<script setup>
import { ElMessage } from 'element-plus'
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { upload, list } from '@/api/index'

const uploadRef = ref(null)

const tableList = ref([{}])

// file文件数量
let fileCount = 0
let tempFileList = []
let pendingUploadFileList = []
let interval = null

onMounted(() => {
  getFileList()
  interval = setInterval(() => {
    getFileList()
  }, 10 * 1000)
})

const getFileList = async () => {
  const { data } = await list()
  if (data && data.list && data.list.length) {
    tableList.value = data.list
  } else {
    tableList.value = []
  }
}

// 选择文件
const changeFile = (file) => {
  tempFileList.push(file)
  pendingUploadFileList.push(file)
  if (!fileCount) {
    const uploadDom = document.querySelector('#el-upload')
    const fileInputDom = uploadDom.getElementsByTagName('input')
    if (fileInputDom && fileInputDom.length > 0 && fileInputDom[0].files && fileInputDom[0].files.length > 0) {
      fileCount = fileInputDom[0].files.length
    }
  }

  let fileSize = file.size
  const FIVE_M = 36 * 1024 * 1024
  //不允许上传大于36M
  if (fileSize > FIVE_M) {
    ElMessage.warning({
      message: '您的上传文件大小过大（36M）。',
      grouping: true,
    })
    pendingUploadFileList.pop()
  }
  //判断文件类型，必须是pdf格式
  let fileName = file.name
  let reg = /\.(pdf)$/
  if (!reg.test(fileName)) {
    ElMessage.warning({
      message: '您的上传文件格式有误， 请上传PDF格式。',
      grouping: true,
    })
    pendingUploadFileList.pop()
  }
  uploadRef.value.submit()
}

// 上传
const uploadFile = async () => {
  resetFiles()
  if (pendingUploadFileList.length) {
    const tmpFiles = [...pendingUploadFileList]
    pendingUploadFileList = []
    const promiseArr = []
    tmpFiles.forEach((v) => {
      promiseArr.push(singleUpload(v))
    })
    try {
      await Promise.all(promiseArr)
      ElMessage.success('上传成功')
    } catch (error) {
      console.error('====>', error)
    } finally {
      // TODO 查列表
      getFileList()
    }
  }
}

// 单个上传
const singleUpload = async (file) => {
  const formData = new FormData()
  formData.append('file', file.raw)
  formData.append('multipartFileForm', new Blob([JSON.stringify({ docId: Date.now(), userId: 1 })], { type: 'application/json' }))
  await upload(formData)
}

// 重置
const resetFiles = () => {
  if (fileCount) {
    tempFileList = []
    fileCount = 0
    uploadRef.value.clearFiles()
  }
}

onBeforeUnmount(() => {
  interval && clearInterval(interval)
})
</script>

<style lang="scss" scoped>
.home-main {
  min-height: 100vh;
  background-image: url('~@/assets/images/home-bg.png');
  background-repeat: no-repeat;
  background-size: 100%;
  header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    text-align: center;
    height: 80px;
    line-height: 80px;
    box-shadow: 0 5px 10px 0 rgba(0, 0, 0, 0.1);
    background: #3f9eff;
    font-size: 24px;
    color: #fff;
    z-index: 99;
  }
  .main-bfc {
    overflow: hidden;
    padding-top: 100px;
    padding-bottom: 20px;
  }
  .main-wrap {
    width: 1200px;
    min-height: calc(100vh - 120px);
    margin: 0 auto;
    background: #fff;
    border-radius: 8px;
    overflow: auto;
    .upload-container {
      width: 800px;
      height: 600px;
      margin: 40px auto;
      border-radius: 12px;
      border: 2px dashed #cee0ff;
      position: relative;
      .flex-column-center {
        img {
          width: 84px;
        }
        .tip {
          margin-top: 10px;
        }
        .upload-btn {
          width: 218px;
          height: 44px;
          line-height: 44px;
          border-radius: 72px;
        }
      }
    }
    .table-container {
      width: 1000px;
      margin: 20px auto;
    }

    .tip {
      text-align: center;
      font-size: 16px;
      font-weight: 400;
      color: #636364;
      line-height: 23px;
    }
    .el-upload {
      .upload-btn {
        width: 106px;
        height: 36px;
        border-radius: 8px;
        text-align: center;
        font-size: 16px;
        font-weight: 400;
        color: #ffffff;
        background: -webkit-gradient(linear, right top, left top, from(#4569ff), to(#3039e7));
        background: linear-gradient(270deg, #4569ff 0%, #3039e7 100%);
        cursor: pointer;
        .upload-img {
          width: 25px;
        }
      }
    }
    .el-table {
      :deep(.file-type-img) {
        width: 22px;
        margin-right: 5px;
      }
      :deep(.table-header) {
        .el-table__cell {
          background: rgb(241, 240, 240);
          color: rgb(76, 75, 75);
        }
      }
      .jxz-status:after {
        content: '';
        animation: dotAnimate 1s infinite;
      }
      .error-status {
        color: red;
      }
      .href-text {
        color: #3039e7;
      }
    }
  }
  @keyframes dotAnimate {
    0%,
    100% {
      content: '';
    }
    25% {
      content: '.';
    }
    50% {
      content: '..';
    }
    75% {
      content: '...';
    }
  }
}
</style>
